import './SignUpLoading.scss'
import qs from 'qs'
import { useRequest } from 'alova'
import PropTypes from 'prop-types'
import { Result, Button } from 'antd'
import { useBoolean, useMount } from "ahooks"
import { useNavigate } from 'react-router-dom'
import { lazy, useState, Suspense } from 'react'

import { Http } from '../../Api'
import { AddIndexdDB, GetIndexedDB } from '../../Utils/IndexedDB'

import { ThemeJSONDefault } from '../../Config/themeList'



const LoadSvg = lazy(() => import('../../Views/LoadSvg'))

const SignUpLoading = ({ Off, data, ModalEvent }) => {
    SignUpLoading.propTypes = { data: PropTypes.object, Off: PropTypes.func, ModalEvent: PropTypes.object }
    const Navigate = useNavigate()
    const NavAdmin = () => Navigate('Admin')
    const NavStart = () => Navigate('Start')

    const [UserInfo, setUserInfo] = useState()
    const [Loading, { toggle }] = useBoolean(true)
    const [Content, setContent] = useState('正在努力登录中...')

    const { send } = useRequest(data => Http({ url: 'posToken', params: data }), { immediate: false })
    const { send: getUser } = useRequest(() => Http({ url: 'getUserInfo' }), { immediate: false })
    const { send: getRoul } = useRequest(path => Http({ url: 'getRolesMenus', path }), { immediate: false })
    const { send: getMenu, } = useRequest(() => Http({ url: 'getProjectMenuOldTree' }), { immediate: false })
    const { send: getClient } = useRequest(() => Http({ url: 'getClientData' }), { immediate: false })

    const { send: getTheme } = useRequest(() => Http({ url: 'getJsonInfoByUuid', params: { uuid: 'theme/theme' } }), { immediate: false })
    const { send: getAdminMenu } = useRequest(() => Http({ url: 'getJsonInfoByUuid', params: { uuid: 'theme/AdminMenu' } }), { immediate: false })
    const { send: getAdminHome } = useRequest(() => Http({ url: 'getJsonInfoByUuid', params: { uuid: 'theme/AdminHome' } }), { immediate: false })
    const { send: getStartColor } = useRequest(() => Http({ url: 'getJsonInfoByUuid', params: { uuid: 'theme/StartColor' } }), { immediate: false })
    const { send: getStartRouter } = useRequest(() => Http({ url: 'getJsonInfoByUuid', params: { uuid: 'theme/StartRouter' } }), { immediate: false })



    const SignUp = async () => {
        try {
            const token = await send(qs.stringify(data))
            const { token_type, access_token } = token
            await AddIndexdDB('token', `${token_type} ${access_token}`)
            setContent('正在获取用户信息...')
            const user = await getUser()
            const [path] = user.userRoles
            await AddIndexdDB('user', user)
            setContent('正在获取项目信息...')
            const [role, menu, redis] = await Promise.all([getRoul([path]), getMenu(), getClient()])
            await Promise.all([
                AddIndexdDB('role', role),
                AddIndexdDB('menu', menu),
                AddIndexdDB('redis', redis.clientData),
                AddIndexdDB('client', redis.tag),
            ])
            setUserInfo({ role: redis.clientData.role[path], name: user.userName })
            getJsonData()
        } catch (err) {
            ModalEvent.emit(err.message)
            Off()
        }
    }

    // AddIndexdDB('home', theme),
    // AddIndexdDB('color', front),
    // AddIndexdDB('router', color),

    // getAdminHome
    // getStartColor
    // getStartRouter


    const getJsonData = async () => {
        // 获取配置
        const theme = await getTheme()
        if (theme?.data === '文件不存在') AddIndexdDB('theme', ThemeJSONDefault)
        else AddIndexdDB('theme', theme)
        const mapping = await getAdminMenu()
        if (mapping?.data === '文件不存在') AddIndexdDB('mapping', {})
        else AddIndexdDB('mapping', mapping)
        const home = await getAdminHome()
        if (home?.data === '文件不存在') AddIndexdDB('home', { module: [], data: {} })
        else AddIndexdDB('home', home)
        const color = await getStartColor()
        if (color?.data === '文件不存在') AddIndexdDB('color', {})
        else AddIndexdDB('color', color)
        const router = await getStartRouter()
        if (router?.data === '文件不存在') AddIndexdDB('router', {})
        else AddIndexdDB('router', router)

        signUpSuccess()
    }

    const signUpSuccess = async () => {
        const config = await GetIndexedDB('config')
        const { loginMethod } = config
        if (loginMethod === 'Admin') NavAdmin()
        else if (loginMethod === 'Start') NavStart()
        else toggle()
    }
    useMount(() => SignUp())

    return (
        <div className="SignUpLoading">
            {Loading ?
                <Suspense>
                    <LoadSvg style={{ '--background': 'transparent', '--stroke': '#212121', height: '100%' }} />
                    <div className="text">{Content}</div>
                </Suspense> :
                <Result
                    status="success"
                    title={`欢迎 ${UserInfo.role || '编外人士'}-${UserInfo.name} 登录平台`}
                    extra={[
                        <Button key="admin" size='large' type="primary" onClick={NavAdmin} > 进入后台 </Button>,
                        <Button key="front" size='large' onClick={NavStart}> 进入大屏 </Button>,
                    ]}
                />
            }
        </div>
    );
};

export default SignUpLoading;